extends Node
class_name AESUtil



# 解密
static func decrypt(data:PoolByteArray,key:String)->PoolByteArray:
	var aes = AESContext.new()
	aes.start(AESContext.MODE_ECB_DECRYPT, key.md5_buffer())
	var decrypted = aes.update(data)
	decrypted = pkcs7_unpadding(decrypted)
	aes.finish()
	return decrypted
static func decrypt_str(data:String,key:String)->String:
	return decrypt(data.to_utf8(),key).get_string_from_utf8()

# 加密
static func encrypt(data:PoolByteArray,key:String)->PoolByteArray:
	var aes = AESContext.new()
	data = pkcs7_padding(data,16)
	aes.start(AESContext.MODE_ECB_ENCRYPT, key.md5_buffer())
	var encrypted = aes.update(data)
	aes.finish()
	return encrypted
# 加密
static func encrypt_str(data:String,key:String)->String:
	return encrypt(data.to_utf8(),key).get_string_from_utf8()

# PKCS7填充
static func pkcs7_padding(data: PoolByteArray, block_size: int) -> PoolByteArray:
	var padding_length = block_size - (data.size() % block_size)
	if padding_length == 0:
		padding_length = block_size  # 如果已满，填充整个块
	var padding = PoolByteArray()
	for i in range(padding_length):
		padding.append(padding_length)  # 填充值为填充字节的长度

	return data + padding

# PKCS7去填充
static func pkcs7_unpadding(data: PoolByteArray) -> PoolByteArray:
	if data.size() == 0:
		return data
	var padding_length = data[data.size() - 1]
	# 确保填充长度有效
	if padding_length > data.size() or padding_length == 0:
		return data  # 填充无效，返回原数据
	# 验证填充内容
	for i in range(data.size() - padding_length, data.size()):
		if data[i] != padding_length:
			return data  # 填充无效，返回原数据
	return data.subarray(0, data.size() - padding_length)  # 返回去除填充后的数据
